<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>链式跟踪监控</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background-color: #f5f5f5;
            color: #333;
        }

        .header {
            background: #fff;
            padding: 20px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            margin-bottom: 20px;
        }

        .header h1 {
            color: #2c3e50;
            font-size: 24px;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 0 20px;
        }

        .search-panel {
            background: #fff;
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 20px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }

        .search-form {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
            align-items: end;
        }

        .form-group {
            display: flex;
            flex-direction: column;
        }

        .form-group label {
            margin-bottom: 5px;
            font-weight: 500;
            color: #555;
        }

        .form-group input,
        .form-group select {
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
        }

        .btn {
            padding: 8px 16px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            transition: background-color 0.2s;
        }

        .btn-primary {
            background-color: #3498db;
            color: white;
        }

        .btn-primary:hover {
            background-color: #2980b9;
        }

        .btn-secondary {
            background-color: #95a5a6;
            color: white;
        }

        .btn-secondary:hover {
            background-color: #7f8c8d;
        }

        .api-list {
            background: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }

        .api-item {
            padding: 15px 20px;
            border-bottom: 1px solid #eee;
            cursor: pointer;
            transition: background-color 0.2s;
        }

        .api-item:hover {
            background-color: #f8f9fa;
        }

        .api-item:last-child {
            border-bottom: none;
        }

        .api-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 8px;
        }

        .api-method {
            display: inline-block;
            padding: 2px 8px;
            border-radius: 3px;
            font-size: 12px;
            font-weight: bold;
            color: white;
        }

        .method-GET {
            background-color: #27ae60;
        }

        .method-POST {
            background-color: #3498db;
        }

        .method-PUT {
            background-color: #f39c12;
        }

        .method-DELETE {
            background-color: #e74c3c;
        }

        .method-METHOD {
            background-color: #9b59b6;
        }

        .api-url {
            font-weight: 500;
            margin-left: 10px;
        }

        .api-status {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .status-badge {
            padding: 2px 8px;
            border-radius: 3px;
            font-size: 12px;
            font-weight: bold;
        }

        .status-success {
            background-color: #d4edda;
            color: #155724;
        }

        .status-error {
            background-color: #f8d7da;
            color: #721c24;
        }

        .api-info {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
            gap: 10px;
            font-size: 13px;
            color: #666;
        }

        .loading {
            text-align: center;
            padding: 40px;
            color: #666;
        }

        .empty {
            text-align: center;
            padding: 40px;
            color: #999;
        }

        .pagination {
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 10px;
            margin-top: 20px;
            padding: 20px;
        }

        .auto-refresh {
            display: flex;
            align-items: center;
            gap: 10px;
            margin-top: 10px;
        }

        .auto-refresh input[type="checkbox"] {
            margin: 0;
        }
    </style>
</head>

<body>
    <div class="header">
        <div class="container">
            <h1>链式跟踪监控</h1>
        </div>
    </div>

    <div class="container">
        <!-- 搜索面板 -->
        <div class="search-panel">
            <div class="search-form">
                <div class="form-group">
                    <label for="searchUrl">URL</label>
                    <input type="text" id="searchUrl" placeholder="请输入URL关键字">
                </div>
                <div class="form-group">
                    <label for="searchMethod">请求方法</label>
                    <select id="searchMethod">
                        <option value="">全部</option>
                        <option value="GET">GET</option>
                        <option value="POST">POST</option>
                        <option value="PUT">PUT</option>
                        <option value="DELETE">DELETE</option>
                    </select>
                </div>
                <div class="form-group">
                    <label for="searchModule">模块</label>
                    <input type="text" id="searchModule" placeholder="请输入模块名">
                </div>
                <div class="form-group">
                    <button type="button" class="btn btn-primary" onclick="searchApiLogs()">搜索</button>
                </div>
                <div class="form-group">
                    <button type="button" class="btn btn-secondary" onclick="loadRecentLogs()">刷新</button>
                </div>
            </div>
            <div class="auto-refresh">
                <input type="checkbox" id="autoRefresh" onchange="toggleAutoRefresh()">
                <label for="autoRefresh">自动刷新 (10秒)</label>
            </div>
        </div>

        <!-- API列表 -->
        <div class="api-list" id="apiList">
            <div class="loading">加载中...</div>
        </div>

        <!-- 分页 -->
        <div class="pagination" id="pagination" style="display: none;">
            <button class="btn btn-secondary" onclick="previousPage()">上一页</button>
            <span id="pageInfo">第 1 页</span>
            <button class="btn btn-secondary" onclick="nextPage()">下一页</button>
        </div>
    </div>

    <script>
        let currentPage = 0;
        let pageSize = 20;
        let autoRefreshInterval = null;

        // 页面加载完成后获取数据
        document.addEventListener('DOMContentLoaded', function () {
            loadRecentLogs();
        });

        // 加载最近的调用链
        function loadRecentLogs() {
            fetch('/chain-trace/api/recent?limit=50')
                .then(response => response.json())
                .then(data => {
                    renderApiList(data);
                })
                .catch(error => {
                    console.error('Error:', error);
                    document.getElementById('apiList').innerHTML = '<div class="empty">加载失败</div>';
                });
        }

        // 搜索API日志
        function searchApiLogs() {
            const url = document.getElementById('searchUrl').value;
            const method = document.getElementById('searchMethod').value;
            const module = document.getElementById('searchModule').value;

            const params = new URLSearchParams();
            if (url) params.append('url', url);
            if (method) params.append('method', method);
            if (module) params.append('module', module);
            params.append('page', currentPage);
            params.append('size', pageSize);

            fetch('/chain-trace/api/search?' + params.toString())
                .then(response => response.json())
                .then(data => {
                    renderApiList(data.data);
                    updatePagination(data);
                })
                .catch(error => {
                    console.error('Error:', error);
                    document.getElementById('apiList').innerHTML = '<div class="empty">搜索失败</div>';
                });
        }

        // 渲染调用链列表
        function renderApiList(chains) {
            const listElement = document.getElementById('apiList');

            if (!chains || chains.length === 0) {
                listElement.innerHTML = '<div class="empty">暂无数据</div>';
                return;
            }

            const html = chains.map(chain => {
                if (chain.url) {
                    // API调用链
                    return `
                        <div class="api-item" onclick="viewTrace('${chain.id}')">
                            <div class="api-header">
                                <div>
                                    <span class="api-method method-${chain.httpMethod}">${chain.httpMethod}</span>
                                    <span class="api-url">${chain.url}</span>
                                </div>
                                <div class="api-status">
                                    <span class="status-badge ${chain.success ? 'status-success' : 'status-error'}">
                                        ${chain.success ? '成功' : '失败'}
                                    </span>
                                    <span>${chain.duration}ms</span>
                                </div>
                            </div>
                            <div class="api-info">
                                <div><strong>类型:</strong> API调用</div>
                                <div><strong>时间:</strong> ${formatTime(chain.startTime)}</div>
                                <div><strong>IP:</strong> ${chain.clientIp || '-'}</div>
                                <div><strong>模块:</strong> ${chain.module || '-'}</div>
                            </div>
                        </div>
                    `;
                } else {
                    // 方法调用链
                    return `
                        <div class="api-item" onclick="viewTrace('${chain.id}')">
                            <div class="api-header">
                                <div>
                                    <span class="api-method method-METHOD">METHOD</span>
                                    <span class="api-url">${chain.method}</span>
                                </div>
                                <div class="api-status">
                                    <span class="status-badge ${chain.success ? 'status-success' : 'status-error'}">
                                        ${chain.success ? '成功' : '失败'}
                                    </span>
                                    <span>${chain.duration}ms</span>
                                </div>
                            </div>
                            <div class="api-info">
                                <div><strong>类型:</strong> 方法调用链</div>
                                <div><strong>时间:</strong> ${formatTime(chain.startTime)}</div>
                                <div><strong>名称:</strong> ${chain.name || '-'}</div>
                                <div><strong>层级:</strong> ${chain.level}</div>
                            </div>
                        </div>
                    `;
                }
            }).join('');

            listElement.innerHTML = html;
        }

        // 查看调用链详情
        function viewTrace(apiId) {
            window.open('/chain-trace/detail/' + apiId, '_blank');
        }

        // 格式化时间
        function formatTime(timestamp) {
            const date = new Date(timestamp);
            return date.toLocaleString('zh-CN');
        }

        // 更新分页信息
        function updatePagination(data) {
            const paginationElement = document.getElementById('pagination');
            const pageInfoElement = document.getElementById('pageInfo');

            if (data.total > pageSize) {
                paginationElement.style.display = 'flex';
                pageInfoElement.textContent = `第 ${currentPage + 1} 页`;
            } else {
                paginationElement.style.display = 'none';
            }
        }

        // 上一页
        function previousPage() {
            if (currentPage > 0) {
                currentPage--;
                searchApiLogs();
            }
        }

        // 下一页
        function nextPage() {
            currentPage++;
            searchApiLogs();
        }

        // 切换自动刷新
        function toggleAutoRefresh() {
            const checkbox = document.getElementById('autoRefresh');

            if (checkbox.checked) {
                autoRefreshInterval = setInterval(loadRecentLogs, 10000);
            } else {
                if (autoRefreshInterval) {
                    clearInterval(autoRefreshInterval);
                    autoRefreshInterval = null;
                }
            }
        }

        // 页面卸载时清理定时器
        window.addEventListener('beforeunload', function () {
            if (autoRefreshInterval) {
                clearInterval(autoRefreshInterval);
            }
        });
    </script>
</body>

</html>